import { IProxy } from '@/typing';
import { catchError, defer, forkJoin, map, Observable, of, Subject } from 'rxjs';
import BaseSourceFetcher from '@/modules/proxy/proxy-source/base-source-fetcher';
import IHelper from '@/services/helper.service';
import axios from 'axios';
import * as cheerio from 'cheerio';
import ILogger from '@/services/logger.service';

export default class ProxySource03 extends BaseSourceFetcher {
  updater$: Subject<IProxy>
  fetch(updater$: Subject<IProxy>) {
    console.log("fetch source 3")
    this.updater$ = updater$
    const pages: string[] = [
      "b97827cc", "4ce63706", "5crfe930", "f3k1d581", "ce1d45977", "881aaf7b5", "eas7a436", "981o917f5", "2d28bd81a", "a42g5985d",
      "came0299", "e92k59727", "242r0e7b5", "bc265a560", "622b6a5d3", "ae3g7e7aa", "b01j07395", "68141a2df", "904545743", "0134c4568",
    ]
    forkJoin(
      [...pages.map(page => this.getPerPage(page))]
    ).subscribe()
  }

  debug() {
    console.log("source3 debug")
    this.getPerPage("b97827cc").subscribe()
  }

  getPerPage(page: string) {
    return defer(() =>
      axios.get('https://ip.ihuan.me/address/5Lit5Zu9.html', {
        params: {
          'page': page
        },
        headers: {
          'Host': 'ip.ihuan.me',
          'Cookie': 'Hm_lvt_8ccd0ef22095c2eebfe4cd6187dea829=1703227925; statistics=821789b99f9168330b06379c53813800; cf_chl_2=fd09ef8bb4180bc; cf_clearance=uXG08aVMFWuLesnHS4Op1QFeeMo.weFwTqVKie8QvRw-1703469198-0-2-235290b9.4a3cda93.7453cf59-160.0.0; Hm_lpvt_8ccd0ef22095c2eebfe4cd6187dea829=1703469206',
          'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
          'sec-ch-ua-mobile': '?0',
          'sec-ch-ua-platform': '"macOS"',
          'upgrade-insecure-requests': '1',
          'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
          'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
          'sec-fetch-site': 'same-origin',
          'sec-fetch-mode': 'navigate',
          'sec-fetch-user': '?1',
          'sec-fetch-dest': 'document',
          'referer': 'https://ip.ihuan.me/address/5Lit5Zu9.html',
          'accept-language': 'zh-CN,zh;q=0.9'
        }
      }).then(d => d.data).catch(error => {
        ILogger.error(`Proxy source 3 fetch error. url=https://ip.ihuan.me/address/5Lit5Zu9.html?page=${page} . At ${IHelper.timeFormatted()}`)
        throw error
      })
    ).pipe(
      map(html => this.parseHtml(html)),
      catchError(() => of([] as IProxy[]))
    )
  }
  parseHtml(html: string) {
    const $ = cheerio.load(html)
    const trList = $("table tbody tr")
    const proxyList: IProxy[] = IHelper.getArray(trList.length).map(idx => this.parseRow(trList.eq(idx)))
    return proxyList
  }

  parseRow(row: cheerio.Cheerio<cheerio.Element>): IProxy {
    const proxy: IProxy = {
      host: row.find("td a").eq(0).text().trim(),
      port: +row.find("td").eq(1).text().trim(),
      last_time: IHelper.timeFormatted(),
      region: "",
      source: "source-03"
    }
    this.updater$.next(proxy)
    return proxy
  }
}